package org.hbhk.hxl.gateway.filter;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class IsolationCounterUtil {
	public static Logger log = LoggerFactory.getLogger(IsolationCounterUtil.class);

	private static LoadingCache<String, AtomicInteger> count = CacheBuilder.newBuilder()
			.expireAfterAccess(60, TimeUnit.SECONDS).expireAfterWrite(60, TimeUnit.SECONDS)
			.build(new CacheLoader<String, AtomicInteger>() {
				@Override
				public AtomicInteger load(String o) throws Exception {
					return new AtomicInteger();
				}
			});

	public static boolean validate(String url, long limits) {
		// 获取当前的时间戳作为key
		try {
			AtomicInteger atomicInteger = count.get(url);
			if (atomicInteger == null) {
				count.put(url, new AtomicInteger(0));
			}
			if (atomicInteger.get() > limits) {
				return false;
			}
			atomicInteger.addAndGet(1);
		} catch (ExecutionException e) {
			log.error(e.getMessage(), e);
		}
		return true;

	}

	public static void decrement(String url) {
		// 获取当前的时间戳作为key
		try {
			synchronized (url) {
				if (count.get(url).get() > 0) {
					count.get(url).addAndGet(-1);
				}
			}

		} catch (ExecutionException e) {
			log.error(e.getMessage(), e);
		}
	}

	public static int getCounter(String url) {
		// 获取当前的时间戳作为key
		try {
			synchronized (url) {
				return count.get(url).get();
			}
		} catch (ExecutionException e) {
			throw new RuntimeException(e);
		}
	}
}
